package com.wstro.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.plugins.Page;
import com.wstro.entity.QuestionEntity;
import com.wstro.entity.QuestionGroupEntity;
import com.wstro.entity.QuestionTypeEntity;
import com.wstro.entity.SysMenuEntity;
import com.wstro.service.*;
import com.wstro.util.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 题目类型
 */
@Controller
@RequestMapping("admin/sys/question")
public class QuestionController extends AbstractController {

    @Resource
    private QuestionService questionService;
    @Resource
    private QuestionGroupService questionGroupService;
    @Resource
    private QuestionTypeService questionTypeService;

    /**
     * 自己的个人信息
     *
     * @return
     */
    @RequestMapping("/getQuestion")
    @RequiresPermissions("sys:user:list")
    @ResponseBody
    public R getQuestion(Integer offset, Integer limit, String sort, String order,
                  @RequestParam(name = "search", required = false) String search) {
        String title = null;
        Map<String, String> searchList = parseObject(search, "q_title");
        if (null != searchList) {
            title = searchList.get("q_title");
        }
        offset = (offset / limit) + 1;
        Boolean flag = null; // 排序逻辑
        if (StringUtils.isNoneBlank(order)) {
            if (order.equalsIgnoreCase("asc")) {
                flag = true;
            } else {
                flag = false;
            }
        }
        if (sort.equals("groupName")){
            sort = "`group`";
        }else if (sort.equals("typeName")){
            sort = "`type`";
        }
        Page<QuestionEntity> questionEntityPage = questionService.queryListByPage(offset, limit, title, sort, flag);
        List<QuestionEntity> questionEntityList = questionEntityPage.getRecords();
        List<QuestionGroupEntity> questionGroupEntities = new ArrayList<>();
        Object object = ehcacheUtil.get("questionGroup", "list");
        if (null != object) {
            if (object instanceof List) {
                logger.info("从缓存中获取值");
                questionGroupEntities =  (List<QuestionGroupEntity>) object;
            }
        }else {
            questionGroupEntities = questionGroupService.queryListByPage(0,500,null,null,false).getRecords();
            ehcacheUtil.put("questionGroup", "list", questionGroupEntities);
        }
        Map<Integer,QuestionGroupEntity> questionGroupEntityMap = questionGroupEntities.stream().collect(Collectors.toMap(QuestionGroupEntity::getId, Function.identity()));

        List<QuestionTypeEntity> questionTypeEntities = new ArrayList<>();
        Object questionTypeObj = ehcacheUtil.get("questionType", "list");
        if (null != questionTypeObj) {
            if (questionTypeObj instanceof List) {
                logger.info("从缓存中获取值");
                questionTypeEntities =  (List<QuestionTypeEntity>) questionTypeObj;
            }
        }else {
            questionTypeEntities = questionTypeService.selectList(null);
            ehcacheUtil.put("questionType", "list", questionTypeEntities);
        }
        Map<Integer,QuestionTypeEntity> questionTypeEntityMap = questionTypeEntities.stream().collect(Collectors.toMap(QuestionTypeEntity::getId,Function.identity()));
        for (int i = 0; i < questionEntityList.size(); i++) {
            questionEntityList.get(i).setGroupName(questionGroupEntityMap.get(questionEntityList.get(i).getGroup()).getName());
            questionEntityList.get(i).setTypeName(questionTypeEntityMap.get(questionEntityList.get(i).getType()).getName());
        }

        PageUtils pageUtil = new PageUtils(questionEntityPage.getRecords(), questionEntityPage.getTotal(), questionEntityPage.getSize(),
                questionEntityPage.getCurrent());
        return R.ok().put("page", pageUtil);
    }

    @RequestMapping("/getQuestionById/{id}")
    @RequiresPermissions("sys:user:list")
    @ResponseBody
    public R getQuestionById(@PathVariable("id") Long id) {
        QuestionEntity questionEntity = questionService.selectById(id);



        return R.ok().put("question", questionEntity);
    }

    @RequestMapping("/type/list")
    //@RequiresPermissions("sys:role:select")
    @ResponseBody
    public R list() {
        // 查询列表数据
        List<QuestionTypeEntity> list = questionTypeService.selectList(null);

        return R.ok().put("list", list);
    }

    @RequestMapping("/save")
    @ResponseBody
    //@RequiresPermissions("sys:user:save")
    public R save(@Valid QuestionEntity questionEntity, BindingResult result)
            throws Exception {
        questionEntity.setStatus(1);
        questionEntity.setCreateTime(JoeyUtil.stampDate(new Date(), DateUtils.DATE_TIME_PATTERN));
        questionService.save(questionEntity);
        return R.ok();
    }
    @RequestMapping("/update")
    @ResponseBody
    //@RequiresPermissions("sys:user:save")
    public R update(@Valid QuestionEntity questionEntity, BindingResult result)
            throws Exception {
        questionEntity.setStatus(1);
        questionEntity.setCreateTime(JoeyUtil.stampDate(new Date(), DateUtils.DATE_TIME_PATTERN));
        questionService.updateById(questionEntity);
        return R.ok();
    }
    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions("sys:user:delete")
    public R delete(@RequestParam("ids") String ids) {
        JSONArray jsonArray = JSONArray.parseArray(ids);
        Long[] idArray = toArrays(jsonArray);
        if (idArray.length < 1) {
            return R.error("删除的试题分类为空");
        }

        for (int i = 0; i < idArray.length; i++) {
            questionService.deleteById(idArray[i].intValue());
        }
        return R.ok();
    }

}
